﻿using Egg.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace db_sync_core.Dto
{
    /// <summary>
    /// 配置
    /// </summary>
    public class Setting
    {
        /// <summary>
        /// 连接列表
        /// </summary>
        public virtual List<SettingConnection> Connections { get; set; } = new List<SettingConnection>();

        /// <summary>
        /// 从文件加载配置
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static Setting LoadFromFile(string path)
        {
            if (!egg.IO.CheckFileExists(path))
            {
                Setting setting = new Setting();
                setting.Connections.Add(new SettingConnection()
                {
                    ConnectionString = "",
                    ConnectionType = DatabaseTypes.Unknow,
                    Name = "测试库"
                });
                setting.SaveToFile(path);
            }
            string json = egg.IO.ReadUtf8FileContent(path);
            return JsonSerializer.Deserialize<Setting>(json) ?? new Setting();
        }

        /// <summary>
        /// 保存到文件
        /// </summary>
        /// <param name="path"></param>
        public void SaveToFile(string path)
        {
            string json = JsonSerializer.Serialize(this);
            egg.IO.WriteUtf8FileContent(path, json);
        }
    }

    /// <summary>
    /// 连接信息配置
    /// </summary>
    public class SettingConnection
    {
        /// <summary>
        /// 连接类型
        /// </summary>
        public string Name { get; set; } = string.Empty;
        /// <summary>
        /// 数据库名称
        /// </summary>
        public string DbName { get; set; } = string.Empty;
        /// <summary>
        /// 数据库用户名
        /// </summary>
        public string UserName { get; set; } = string.Empty;
        /// <summary>
        /// 连接类型
        /// </summary>
        public DatabaseTypes ConnectionType { get; set; } = DatabaseTypes.Unknow;
        /// <summary>
        /// 连接字符串
        /// </summary>
        public string ConnectionString { get; set; } = string.Empty;
    }
}
